import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { LocalStorage } from 'quasar'

/* 项目全局变量配置 */
export const useLayoutStore = defineStore('layout', () => {
  // 首页
  const mainPage: WJ.MenuItem = {
    id: '0',
    pid: '0',
    name: '首页',
    sort: 0,
    icon: 'home',
    auth: '',
    path: '/'
  }

  const menuKey = 'menu';
  const menu = LocalStorage.getItem<Array<WJ.MenuItem>>(menuKey)
  // 原始的菜单数据(平级)
  const menuList = ref<Array<WJ.MenuItem>>(menu ? menu : []);
  // Tab栏的List
  const tabList = ref<Array<WJ.MenuItem>>([]);
  // 面包屑
  const crumbsList = ref<Array<WJ.MenuItem>>([]);
  // 左边侧边栏宽度
  const leftDrawerWeight = ref(250);

  // 菜单排序
  const menuSort = (a: WJ.MenuItem, b: WJ.MenuItem) => a.sort - b.sort

  // 树形菜单数据,操作中过滤隐藏菜单
  const menuTree = computed(() => {
    // 将子元素依次放入父元素中
    const res: Array<WJ.MenuItem> = [];
    menuList.value.forEach((item) => {
      const parent = menuIdMap.value.get(item.pid);
      if (parent) {
        const pc = (parent.children || (parent.children = []));
        pc.indexOf(item) === -1 ? pc.push(item) : ''
        pc.sort(menuSort)
      } else {
        item.isHide ? '' : res.push(item)
      }
    });
    res.sort(menuSort)
    return res;
  })
  /**
   * id:menuitem
   */
  const menuIdMap = computed(() => {
    const map = new Map<string, WJ.MenuItem>();
    menuList.value.forEach((item) => {
      map.set(item.id, item);
    });
    return map
  })

  /**
    * path:menuitem
    */
  const menuPathMap = computed(() => {
    const map = new Map<string, WJ.MenuItem>();
    menuList.value.forEach((item) => {
      map.set(item.path, item);
    });
    return map
  })

  /**
 * true表示是http或https开头的url
 * @param url 待检测url
 */
  function isHttp(url: string) {
    return url.indexOf('http') !== -1;
  };

  function toBind(item: WJ.MenuItem) {
    return isHttp(item.path)
      ? {
        path: '/outside-link',
        query: {
          url: item.path,
        },
      }
      : item.path
  }

  // 递归向上获取所有父节点
  function findP(item: WJ.MenuItem) {
    const result: Array<WJ.MenuItem> = []
    const findFn = (i: WJ.MenuItem) => {
      result.push(i)
      if (i.pid !== '0') {
        const it = menuIdMap.value.get(i.pid);
        if (it) {
          findFn(it)
        }
      }
    }
    findFn(item);
    return result.reverse();
  }
  return {
    menuList, tabList, crumbsList,
    menuTree, findP, menuPathMap,
    menuIdMap, mainPage, leftDrawerWeight, menuKey, toBind, isHttp
  }
});


/* 项目权限 */
export const useAuthStore = defineStore('auth', () => {
  // token
  const token = ref('');

  return {
    token
  }
}, { persist: true });
